//
//  ViewController.m
//  LocalServerWKWebView
//
//  Created by wanba on 2018/10/9.
//  Copyright © 2018年 wanba. All rights reserved.
//

#import "ViewController.h"
#import <WebKit/WebKit.h>
#import "LocalWebServerManager.h"

@interface ViewController ()<WKScriptMessageHandler, WKNavigationDelegate>
@property (nonatomic, weak) WKWebView *webView;
@end

@implementation ViewController
- (void)dealloc {
    [[LocalWebServerManager sharedInstance] stop];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [[LocalWebServerManager sharedInstance] start];
    
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://localhost:%ld/index.html", [[LocalWebServerManager sharedInstance] port]]]]];
}

- (WKWebView *)webView {
    if (!_webView) {
        
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        // 创建UserContentController（提供JavaScript向webView发送消息的方法）
        WKUserContentController* userContent = [[WKUserContentController alloc] init];
        // 添加消息处理  animationMethod 这个方法一会要与JS里面的方法写的一样
        [userContent addScriptMessageHandler:self name:@"animationMethod"];
        // 将UserConttentController设置到配置文件
        config.userContentController = userContent;
        
        config.suppressesIncrementalRendering = YES; // 是否支持记忆读取
        [config.preferences setValue:@YES forKey:@"allowFileAccessFromFileURLs"];//支持跨域
        [config setValue:@YES forKey:@"allowUniversalAccessFromFileURLs"]; //支持跨域
        
        WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) configuration:config];
        webView.scrollView.scrollEnabled = NO;
        webView.opaque = NO;
        webView.backgroundColor = [UIColor clearColor];
        webView.navigationDelegate = self;
        [self.view addSubview:webView];
        _webView = webView;
        
    }
    return _webView;
}

- (void)dismissWebView {
    self.webView.hidden = YES;
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@""]]];
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    // 判断是否是调用原生的
    if ([@"animationMethod" isEqualToString:message.name]) {
        // 判断message的内容，然后做相应的操作
        if ([@"complete" isEqualToString:message.body]) {
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                [self dismissWebView];
            }];
        }
    }
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    [webView evaluateJavaScript:[NSString stringWithFormat:@"createObject(\"%@\", \"%@\", \"%.1f\", \"%zd\");", @"huanqiu", @"animation", 1.0, 0] completionHandler:^(id _Nullable response, NSError * _Nullable error) {
    }];
}


- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler
{
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        NSURLCredential *card = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
        completionHandler(NSURLSessionAuthChallengeUseCredential, card);
    }
}

@end
